import {AfterViewInit, Directive, HostListener, Input, ViewContainerRef} from '@angular/core';
import * as _ from 'lodash';

@Directive({
  selector: '[appUiToggleClass]'
})
export class UiToggleClassDirective implements AfterViewInit {
  @Input() appUiToggleClass: String;
  @Input() dateTarget: String;

  constructor(public viewContainerRef: ViewContainerRef) {
  }


  ngAfterViewInit(): void {
  }

  @HostListener('click', ['$event'])
  onClick(e) {
    console.log(111)

    const el = this.viewContainerRef.element.nativeElement;
    e.preventDefault();
    const classes = this.appUiToggleClass.split(','),
      targets = (this.dateTarget && this.dateTarget.split(',')) || Array(el);
    let key = 0;
    _.forEach(classes, function (_class) {
      const target = targets[(targets.length && key)];
      if (_class.indexOf('*') !== -1) {
        magic(_class, target);
      }
      $(target).toggleClass(_class);
      key++;
    });
    $(el).toggleClass('active');

    function magic(_class, target) {
      const patt = new RegExp('\\s' +
        _class.replace(/\*!/g, '[A-Za-z0-9-_]+').split(' ').join('\\s|\\s') +
        '\\s', 'g');
      let cn = ' ' + $(target)[0].className + ' ';
      console.log(cn)
      while (patt.test(cn)) {
        cn = cn.replace(patt, ' ');
      }
      $(target)[0].className = _.trim(cn);
    }

  }
}
